/*
 Xern Entity Relocation Network
 Copyright (C) 2011 Ronie Salgado <roniesalg@gmail.com>

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE.
*/

#include "Xern/Log.hpp"
#include "Xern/Engine.hpp"
#include "Xern/Exceptions.hpp"
#include "Xern/FileSystem.hpp"
#include "Xern/PluginFactory.hpp"
#include "Xern/ResourceManager.hpp"

#include "PdLoader.hpp"

namespace XernPd
{
	static PluginFactory<PdLoader> pdLoaderFactory("ResourceLoader", "PdLoader");

	PdLoader::PdLoader()
	{
		int major, minor, bugfix;
		sys_getversion(&major, &minor, &bugfix);
		LogConsole->Notify("Pure Data Version %d.%d-%d", major, minor, bugfix);
	}

	PdLoader::~PdLoader()
	{
	}

	bool PdLoader::CanLoadResource(const std::string &filename, const std::string &group) const
	{
		std::string ext = FileExtension(filename);
		return ext == ".pd";
	}

	bool PdLoader::CanLoadResource(const std::string &mime) const
	{
		return mime == "audio/x-pd";
	}

	boost::shared_ptr<IResource>
	PdLoader::LoadResource(const std::string &filename, const std::string &group, const std::string &path) const
	{
		assert(CanLoadResource(filename, group));

		// Create the pure data context.
		pd_context_t *context = sys_createcontext(1, 0, 1, 2, 44100);

		// Set the current context.
		sys_makecurrent(context);

		// Load the file.
		int res = sys_loadfile(".", path.c_str());
		if(res < 0)
			throw XernException("Failed to load pure data file.");

		// Create the sampler.
		boost::shared_ptr<PDSampler> sampler(new PDSampler(context));

		// Return the sampler.
		return sampler;
	}

	boost::shared_ptr<IResource>
	PdLoader::LoadResource(const std::string &mime, boost::shared_ptr<IDataFilter> data) const
	{
		return boost::shared_ptr<IResource> ();
	}

}
